from fastapi import APIRouter, Depends, HTTPException, status

from app.dependencies_json import get_auth_service, get_current_user
from app.models.schemas import APIResponse, UserCreate, UserLogin, Token, UserInfo
from app.services.json_auth_service import JSONAuthService

router = APIRouter()

@router.post("/register", response_model=APIResponse[UserInfo])
def register(
    user_data: UserCreate,
    auth_service: JSONAuthService = Depends(get_auth_service)
):
    """用户注册"""
    try:
        user_info = auth_service.create_user(user_data)
        return APIResponse(
            message="用户注册成功",
            data=user_info
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册失败"
        )

@router.post("/login", response_model=APIResponse[Token])
def login(
    login_data: UserLogin,
    auth_service: JSONAuthService = Depends(get_auth_service)
):
    """用户登录"""
    try:
        token = auth_service.login(login_data)
        if not token:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )

        return APIResponse(
            message="登录成功",
            data=token
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录失败"
        )

@router.post("/refresh", response_model=APIResponse[Token])
async def refresh_token(
    refresh_token: str,
    db: AsyncSession = Depends(get_db_session),
    auth_service: AuthService = Depends(get_auth_service)
):
    """刷新访问令牌"""
    try:
        token = await auth_service.refresh_token(refresh_token, db)
        if not token:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的刷新令牌"
            )
        
        return APIResponse(
            message="令牌刷新成功",
            data=token
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="令牌刷新失败"
        )

@router.post("/logout", response_model=APIResponse[bool])
async def logout(
    current_user: User = Depends(get_current_user)
):
    """用户登出"""
    # 在实际实现中，可以将令牌加入黑名单
    # 这里简单返回成功
    return APIResponse(
        message="登出成功",
        data=True
    )

@router.get("/me", response_model=APIResponse[UserInfo])
async def get_current_user_info(
    current_user: User = Depends(get_current_user),
    auth_service: AuthService = Depends(get_auth_service)
):
    """获取当前用户信息"""
    user_info = auth_service._user_to_info(current_user)
    return APIResponse(
        message="获取用户信息成功",
        data=user_info
    )

@router.get("/permissions", response_model=APIResponse[list])
async def get_user_permissions(
    current_user: User = Depends(get_current_user)
):
    """获取用户权限"""
    # 根据用户角色返回权限列表
    permissions = []
    
    if current_user.role == "admin":
        permissions = [
            "task:create", "task:read", "task:update", "task:delete",
            "system:manage", "user:manage"
        ]
    elif current_user.role == "user":
        permissions = [
            "task:create", "task:read", "task:update", "task:delete"
        ]
    
    return APIResponse(
        message="获取权限列表成功",
        data=permissions
    )
